package com.hemaapp.yjnh.present;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;

import com.alipay.sdk.app.PayTask;
import com.android.uu.utils.uuUtils;
import com.hemaapp.BaseConfig;
import com.hemaapp.yjnh.alipay.Result;
import com.hemaapp.yjnh.bean.Address;
import com.hemaapp.yjnh.bean.BlogDetail;
import com.hemaapp.yjnh.bean.BlogDetailBySpec;
import com.hemaapp.yjnh.bean.Cart;
import com.hemaapp.yjnh.bean.ClientInfor;
import com.hemaapp.yjnh.bean.SubOrder;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.bean.WeixinTrade;
import com.hemaapp.yjnh.listener.BuyConfirmView;
import com.hemaapp.yjnh.model.BuyConfirmTask;
import com.hemaapp.yjnh.view.BaseButtonDialog;
import com.hemaapp.yjnh.view.PayPasswordDialog;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.unionpay.UPPayAssistEx;

import java.math.BigDecimal;
import java.util.ArrayList;

import xtom.frame.util.XtomSharedPreferencesUtil;
import xtom.frame.util.XtomToastUtil;

/**
 * 类描述：确认订单Present
 * 创建人：GuiyouZhang
 * 创建时间：2016/9/2 14:13
 * 修改备注：
 */
public class BuyConfirmPresent {

    Activity mActivity;
    BuyConfirmView mView;
    BuyConfirmTask mTask;
    IWXAPI msgApi;//微信

    private String keytype;//订单类型	1:从购物车生成的订单;2：直接购买;3：定制订单;4：预约型订单
    private ClientInfor infor;//账户信息 	包含了粮票和账户余额等信息
    private BlogDetail blog;//购买的单个商品
    private BlogDetailBySpec blogDetail;//某个规格的商品信息
    private ArrayList<Cart.ChildItem> cartItems;//购物车中进行结算的商品

    private Address mAddress;
    private double mFreight = 0.0;//运费
    private int mBuyCount = 0;//商品总数量
    private double mBalance = 0.0;//当前账户余额
    private double mAvailCoupons = 0.0;//当前账户可用粮票数
    private double mNeedCoupons = 0.0;//一共需要粮票数
    private double mTotalFee = 0.0;//最终总费用，包含粮票
    private double mFinalCoupons = 0.0;//最终使用的粮票数
    private double mFinalCash = 0.0;//最终使用的现金
    private String mFriendNum;//代付人
    private SubOrder mOrder;//最终生成的订单
    //发票信息
    private int mInvoiceType = 3;//发票类型：1纸质发票，2电子发票，3无CE发票
    private String mInvoicehead = "";//发票抬头
    private String mInvoiceEmail = "无";//电子发票的邮箱地址
    private String mInvoiceContent = "无";//发票内容

    public BuyConfirmPresent(Activity activity, BuyConfirmView buyConfirmView, User user, String type) {
        this.mActivity = activity;
        this.mView = buyConfirmView;
        this.keytype = type;
        mTask = new BuyConfirmTask(mActivity, user, this);
        msgApi = WXAPIFactory.createWXAPI(mActivity, null);
        msgApi.registerApp(BaseConfig.APPID_WEIXIN);
    }

    public void init() {
        mView.setBlogs();//显示商品
        mTask.getClientInfo();//必须要在setBlogs之后
    }

    public void setClientInfor(ClientInfor infor) {
        this.infor = infor;
        mBalance = Double.parseDouble(infor.getFeeaccount());
        mAvailCoupons = Double.parseDouble(infor.getScore());
        mView.setClientInfo(mBalance, mAvailCoupons);
        if (keytype.equals("1") || keytype.equals("2"))//实物类商品需要去获取地址和运费
            mTask.getAddressList();
        else//预约型订单直接计算总额
            setTotalFee();
    }

    public void setInvoiceInfo(int invoiceType, String header, String email, String content) {
        mInvoiceType = invoiceType;
        mInvoicehead = header;
        mInvoiceEmail = email;
        mInvoiceContent = content;
    }

    public void beforeLoad() {
        mView.beforeLoading();//开始加载网络数据
    }

    public void loadFinish() {
        mView.loadingFinish();
    }

    public void onNetFailed(String content) {
        XtomToastUtil.showShortToast(mActivity, content);
    }

    public void setBlog(BlogDetail blog) {
        this.blog = blog;
    }

    public void setBlogDetail(BlogDetailBySpec blogDetail) {
        this.blogDetail = blogDetail;
    }

    public void setFriendNum(String mFriendNum) {
        this.mFriendNum = mFriendNum;
    }

    public void setCartItems(ArrayList<Cart.ChildItem> cartItems) {
        this.cartItems = cartItems;
    }

    public void setNeedScores(double needCoupons) {
        BigDecimal bg = new BigDecimal(needCoupons);
        this.mNeedCoupons = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    public double getNeedCoupons() {
        return mNeedCoupons;
    }

    public double getFinalCash() {
        return mFinalCash;
    }

    public double useFoodStamp(boolean use) {
        if (use) {
            //检查粮票
            if (mAvailCoupons >= mNeedCoupons) {
                mFinalCoupons = mNeedCoupons;
            } else {//如果可用粮票不够支付这两种粮票支付方式
                mFinalCoupons = mAvailCoupons;//可用粮票部分全部用于支付现金部分的粮票
            }
            mFinalCash = mTotalFee - mFinalCoupons;
        }else {
            mFinalCoupons = 0.0;
            mFinalCash = mTotalFee;
        }
        return mFinalCoupons;
    }

    public Address getAddress() {
        return mAddress;
    }

    public void setAddress(Address address) {
        this.mAddress = address;
        mView.setAddress(address);//显示地址，或者提示设置地址
        if (address == null) {
            setFreight("0");//运费临时为0，不去计算
            return;
        }
        if (keytype.equals("1")) {// 购物车
            StringBuffer blog_ids = new StringBuffer();
            StringBuffer spec_ids = new StringBuffer();
            StringBuffer buycounts = new StringBuffer();
            for (Cart.ChildItem item : cartItems) {
                blog_ids.append(item.getKeyid()).append(",");
                spec_ids.append(item.getSpecid()).append(",");
                buycounts.append(item.getBuycount()).append(",");
            }
            blog_ids.deleteCharAt(blog_ids.length()-1);
            spec_ids.deleteCharAt(spec_ids.length()-1);
            buycounts.deleteCharAt(buycounts.length()-1);
            mTask.getTotalFreight(blog_ids.toString(), spec_ids.toString(), buycounts.toString(),
                    address.getId());
        } else if (keytype.equals("2")) {// 立即购买
            if (blogDetail != null) {
                mTask.getTotalFreight(blog.getId(), blogDetail.getId(), mBuyCount+"", address.getId());
            }else
                mTask.getTotalFreight(blog.getId(), "", mBuyCount+"", address.getId());
        }
    }

    public void setFreight(String express) {
        this.mFreight = Double.parseDouble(express);
        mView.setFreight(uuUtils.formatAfterDot2(express));
        setTotalFee();
    }

    public void setBuyCount(int mBuyCount) {
        this.mBuyCount = mBuyCount;
    }

    public double getTotalFee() {
        return mTotalFee;
    }

    private void setTotalFee() {
        double totalPrice = 0.0;
        if (keytype.equals("1")) {//购物车
            for (int i = 0; i < cartItems.size(); i++) {
                double price = Double.parseDouble(cartItems.get(i).getPrice());
                int count = Integer.parseInt(cartItems.get(i).getBuycount());
                totalPrice += price * count;
            }
        }else {//立即购买、预约订单
            if (blogDetail != null) {
                totalPrice += mBuyCount * Double.parseDouble(blogDetail.getPrice());
            }else {
                totalPrice += mBuyCount * Double.parseDouble(blog.getPrice());
            }
        }
        BigDecimal bg = new BigDecimal(totalPrice+mFreight);
        mTotalFee = mFinalCash = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        mView.setTotalFee(mTotalFee+"");
    }

    public void submitOrder(final String contact_name, final String contact_tel, final String startdate) {
        if ((keytype.equals("1") || keytype.equals("2")) && mAddress == null) {
            XtomToastUtil.showShortToast(mActivity, "请选择收货地址");
            return;
        }
        //①没有选择支付方式，而且需要支付现金
        //②无需支付现金，但不必要支付粮票
        if (mView.getPayment() == -1 && mFinalCash > 0) {
            XtomToastUtil.showShortToast(mActivity, "请选择支付方式");
            return;
        }
        if (mView.getPayment() == 3 && !msgApi.isWXAppInstalled()) {//如果选择了微信支付，那么先判断是否安装了微信
            XtomToastUtil.showShortToast(mActivity, "未检测到您手机的微信");
            return;
        }
        if (keytype.equals("1")) {//购物车
            String keyId = "";
            StringBuffer buffer = new StringBuffer();
            for (int i = 0; i < cartItems.size(); i++) {
                buffer.append(cartItems.get(i).getId()).append(",");
            }
            buffer.deleteCharAt(buffer.length() - 1);
            keyId = buffer.toString();
            mTask.submitOrder(keytype, keyId, "无", "", mAddress.getId(), mBuyCount+"", "无", "无", "无");
        }else if (keytype.equals("2")) {//立即购买
            String specId = "0";
            if (blogDetail != null) {
                specId = blogDetail.getId();
            }
            mTask.submitOrder(keytype, blog.getId(), specId, "", mAddress.getId(), mBuyCount+"", "无", "无", "无");
        }else if (keytype.equals("3")) {//定制订单
        }else if (keytype.equals("4")) {//预约型订单
            mView.showAlertDialog("距离服务开始48小时之内，不能取消预约和申请退款。\n确认继续支付？", "确定", new BaseButtonDialog.OnButtonListener() {
                @Override
                public void onLeftButtonClick(BaseButtonDialog dialog) {

                }

                @Override
                public void onRightButtonClick(BaseButtonDialog dialog) {
                    dialog.cancel();
                    mTask.submitOrder(keytype, blog.getId(), "无", "", "无", mBuyCount+"", contact_name, contact_tel, startdate);
                }
            });
        }
    }

    /**订单提交成功，然后去付款
     * @param orders
     */
    public void onOrderSumbitSuccess(SubOrder orders) {
        this.mOrder = orders;
        if (mView.getPayment() != 5 && (mView.getPayment() == 4 || mFinalCoupons > 0))//当需要扣除粮票或者余额的时候，需要输入支付密码
            mView.showPayPwdDialog(new PayPasswordDialog.onPasswordClickListener() {
                @Override
                public void onPasswordConfirm(String password) {
                    toTrade(password);
                }

                @Override
                public void onPasswordCancel() {
                    mView.toNextPage(mOrder.getBill_ids());
                }
            });
        else
            toTrade("");
    }

    private void toTrade(String password) {
        int payment = mView.getPayment();//1支付宝，2银联，3微信，4余额，5朋友代付，-1没有选择支付方式
        if (mFinalCash == 0) {//如果现金部分为0，那么调用全粮票支付
            mTask.scoreRemove(mOrder.getBill_ids(), mFinalCoupons+"", password);
            return;
        }else if (payment == 1) {
            mTask.alipayTrade(mOrder.getBill_ids(), mFinalCash+"", mFinalCoupons+"", password);
        }else if (payment == 2) {
            mTask.uppayTrade(mOrder.getBill_ids(), mFinalCash+"", mFinalCoupons+"", password);
        }else if (payment == 3) {
            mTask.weixinTrade(mOrder.getBill_ids(), mFinalCash+"", mFinalCoupons+"", password);
        }else if (payment == 4) {
//            if (mFinalCash > mBalance) { // 余额不足
//                XtomToastUtil.showShortToast(mActivity, "余额不足，请先充值");
//                mView.toNextPage(mOrder.getBill_ids());
//            }else
                mTask.feeaccountRemove(mOrder.getBill_ids(), mFinalCash+"", mFinalCoupons+"", password);
        }else if (payment == 5) {
            mTask.payByFriend(mOrder.getBill_ids(), mFriendNum);
        }
    }

    public void onPaySuccess() {
        if (mView.getPayment() == 5)
            mView.showTextDialog("下单成功，等待付款");
        else
            mView.showTextDialog("支付成功");
        if (mInvoiceType != 3) {
            mTask.saveInvoice(mOrder.getBill_ids(), mInvoiceType+"", mInvoicehead,
                    mFinalCash+"", mInvoiceEmail, mInvoiceContent);
        }else
            mView.toNextPage(mOrder.getBill_ids());
    }

    public void onPayFailed(String reason) {
        if (TextUtils.isEmpty(reason))
            XtomToastUtil.showShortToast(mActivity, "支付失败，请稍后再试");
        else
            XtomToastUtil.showShortToast(mActivity, "支付失败，"+reason);
        mView.toNextPage(mOrder.getBill_ids());
    }

    public void onInvoiceSaveFinish(String success) {
        mView.showTextDialog(success);
        mView.toNextPage(mOrder.getBill_ids());
    }

    /**后台验签成功后，调本地支付接口
     * @param orderInfo
     */
    public void onAlipayPay(String orderInfo) {
        new AlipayThread(orderInfo).start();
    }

    /**后台验签成功后，调本地支付接口
     * @param orderInfo
     */
    public void onUniPay(String orderInfo) {
//        UPPayAssistEx.startPayByJAR(mActivity, com.unionpay.uppay.PayActivity.class, null, null,
//                orderInfo, BaseConfig.UNIONPAY_TESTMODE);
        UPPayAssistEx.startPay (mActivity, null, null, orderInfo, BaseConfig.UNIONPAY_TESTMODE);
    }

    /**后台验签成功后，调本地支付接口
     * @param trade
     */
    public void onWechatPay(WeixinTrade trade) {
        msgApi.registerApp(BaseConfig.APPID_WEIXIN);
        PayReq request = new PayReq();
        request.appId = trade.getAppid();
        request.partnerId = trade.getPartnerid();
        request.prepayId = trade.getPrepayid();
        request.packageValue = trade.getPackageValue();
        request.nonceStr = trade.getNoncestr();
        request.timeStamp = trade.getTimestamp();
        request.sign = trade.getSign();
        msgApi.sendReq(request);
    }

    public void onUniPayFinish(Intent data) {
        if (data == null) {
            return;
        }
        String str = data.getExtras().getString("pay_result");
        if (str.equalsIgnoreCase("success")) {
            onPaySuccess();
        } else if (str.equalsIgnoreCase("fail")) {
            onPayFailed("");
        } else if (str.equalsIgnoreCase("cancel")) {
            onPayFailed("您取消了支付");
        }
    }

    public void onWechatPayFinish() {
        String weixinpay = XtomSharedPreferencesUtil.get(mActivity, "weixinpay");
        if (weixinpay != null && (weixinpay.equals("1"))) {//说明是从微信支付完成后返回
            XtomSharedPreferencesUtil.save(mActivity, "weixinpay", "0");
            String status = XtomSharedPreferencesUtil.get(mActivity, "status");
            if ("-1".equals(status)) {  //支付失败
                onPayFailed("");
            } else if ("-2".equals(status)) { //支付取消
                onPayFailed("您取消了支付");
            } else {
                onPaySuccess();
            }
        }
    }

    /**
     * 调支付宝app的线程
     */
    private class AlipayThread extends Thread {
        String orderInfo;

        public AlipayThread(String orderInfo) {
            this.orderInfo = orderInfo;
        }

        @Override
        public void run() {
            // 构造PayTask 对象
            PayTask alipay = new PayTask(mActivity);
            String result = alipay.pay(orderInfo);

            Message msg = new Message();
            msg.obj = result;
            Looper.prepare();
            new Handler(){
                @Override
                public void handleMessage(Message msg) {
                    Result result = new Result((String) msg.obj);
                    int staus = result.getResultStatus();
                    switch (staus) {
                        case 9000:
                            onPaySuccess();
                            break;
                        default:
                            onPayFailed(result.getResult());
                            break;
                    }
                }
            }.sendMessage(msg);
            Looper.loop();
        }
    }
}
